//
//  RHMEDevLoadVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/2/29.
//

#import "RHMEDevLoadVC.h"
#import "RHMELoadCell.h"
#import "DevChartParamsModel.h"
#import "SYChartTool.h"
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"
#import "RHDeviceDataSectionView.h"
#import "WSDatePickerView.h"
#import "RHMEDevLoadFullVC.h"

@interface RHMEDevLoadVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) NSArray *sectionTitleArr;
@end

@implementation RHMEDevLoadVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self createData];
    [self setupUI];
    [self getData];
}

-(void)createData
{
    self.sectionTitleArr = @[@"负载".rh_localized];
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"DeviceBatteryLoadChart"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    
    if(self.packSN){
        NSString *voltKey = [NSString stringWithFormat:@"Pck_CellV_%ld",self.cellIndex];
        NSString *tempKey = [NSString stringWithFormat:@"Pck_Tmp_%ld",self.cellIndex];
        NSDictionary *dic = @{@"chartParams":@[
            @[
                @{
                    @"nickname": voltKey,
                    @"comment": @"电芯电压",
                    @"unit": @"MV",
                    @"min": @(0),
                    @"max": @(456498454),
                    @"type": @"number",
                    @"format": @"float",
                    @"alias": @"电芯电压"
                },
                @{
                    @"nickname": tempKey,
                    @"comment": @"电芯温度",
                    @"unit": @"℃",
                    @"min": @(0),
                    @"max": @(1000),
                    @"type": @"number",
                    @"format": @"float",
                    @"alias": @"电芯温度"
                }
            ]
        ]};
        self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dic];
    }
    
}

-(void)setupUI
{
  
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setEstimatedSectionFooterHeight:0];
    [_tableView setSectionFooterHeight:0];
    [_tableView registerClass:[RHMELoadCell class] forCellReuseIdentifier:@"RHMELoadCell"];
  
    _tableView.estimatedRowHeight = 380;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getData];
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
}

-(void)getData
{
    [self.chartParamsModel.chartList enumerateObjectsUsingBlock:^(DevChartModel  *_Nonnull chartModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [self getDataFromNetwork:chartModel];
    }];
}

- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    
    if (!self.deviceModel) {
        [self.tableView endHeaderRefresh];
        return;
    }
    [QMUITips showLoadingInView:self.view];
    NSMutableArray *keys = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [keys addObject:fileld.keyCode];
    }

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    NSString *endpointCode = @"EMS";
    NSString *sn = @"E10000000086";
    if(self.packSN){
        endpointCode = @"Pack";
        sn = self.packSN;
    }
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":endpointCode,
                           @"keyCodes":keys,
                           @"endpointSn":sn,
                           @"startTimestamp":begin_time,
                           @"endTimestamp":end_time
    };
   
    [BaseModel startWithCompletionAPIKey:D_getEndpointDataByTime argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSArray class]]){
                NSArray *dataArr = request.responseObject[@"data"];
                
                //为了让图表显示,造点假数据
                if(dataArr.count == 0){
                    [chartModel creatDefaultChartDataWithChartModel];
                }else{
                    chartModel.allDataArray = dataArr;
                }
                [self.tableView reloadData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   return self.chartParamsModel.chartList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RHDeviceDataSectionView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    if(header == nil){
        header = [[RHDeviceDataSectionView alloc]initWithReuseIdentifier:@"header"];
    }
    kWeakSelf;
    header.seeMoreBlock = ^{
        [weakSelf fullAction:section];
    };
 
    header.titleLab.text = self.sectionTitleArr[section];
    [header hideArrowView:NO];
    
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 1){
        return 15;
    }
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSLog(@"---->返回组尾:%ld",section);
    if(section == 0){
        UITableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer_0"];
        if(footer == nil){
            footer = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"footer_0"];
            footer.backgroundColor = CFTabViewBgColor;
        }
        return footer;
    }else if(section == 1){
        UITableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer_1"];
        if(footer == nil){
            footer = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"footer_1"];
            footer.frame = CGRectMake(0, 0, kUI_WINDOW_W, 10);
            UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
            footView.backgroundColor = [UIColor clearColor];
            UIView *bgView = [[UIView alloc]init];
            [footView addSubview:bgView];
            bgView.backgroundColor = [UIColor whiteColor];
            bgView.frame = CGRectMake(15, 0, kUI_WINDOW_W-30, 10);
            bgView.layer.cornerRadius = 5;
            bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
            [footer addSubview:footView];
        }
       
        return footer;
    }
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"----->返回:%ld组 %ld行",indexPath.section,indexPath.row);
  
        //曲线
        RHMELoadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMELoadCell"];
        DevChartModel *chartModel = self.chartParamsModel.chartList[indexPath.row];

        NSString *type = @"Day";
        if (chartModel.monthParams.count>0) {
            type = @"Month";
        }
        if (chartModel.yearParams.count>0) {
            type = @"Year";
        }
       
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setChartModel:chartModel];
        kWeakSelf;
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.row];
        };
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
//            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        return cell;
   
}


#pragma mark -----  Action
- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel = self.chartParamsModel.chartList[index];
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
    
    DevChartModel *model = [[DevChartModel alloc] init];
    
    model.y2_unit = chartModel.y2_unit;
    model.y2_max = chartModel.y2_max;
    model.y2_min = chartModel.y2_min;
    model.y1_unit = chartModel.y1_unit;
    model.y1_max = chartModel.y1_max;
    model.y1_min = chartModel.y1_min;
    model.isAllowScale = YES;
    model.yAxisArray = [chartModel.yAxisArray mutableCopy];
    model.xTitlesArray = [chartModel.xTitlesArray mutableCopy];
    model.mYDataArray = [chartModel.mYDataArray mutableCopy];
    model.allDataArray = [chartModel.allDataArray mutableCopy];
    model.selectArray = [chartModel.selectArray mutableCopy];
    model.yearParams = [chartModel.yearParams mutableCopy];
    model.monthParams = [chartModel.monthParams mutableCopy];
    model.dayParams = [chartModel.dayParams mutableCopy];
    model.params = [chartModel.params mutableCopy];
    model.curTime = chartModel.curTime;
    model.timeType = chartModel.timeType;
    RHMEDevLoadFullVC *vc = [[RHMEDevLoadFullVC alloc] initWithModel:chartModel chartType:self.chartParamsModel.type deviceModel:self.deviceModel toolType:type];
    [self.navigationController pushViewController:vc animated:NO];
}

#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------

#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.row];
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        if (chartModel.timeType == TimeType_Day) {
            [self getDataFromNetwork:chartModel];
        }else if (chartModel.timeType == TimeType_Month){
//            [self getYearOrMonth:YES model:chartModel];
            [self reloadTableCell:indexpath];
        }else if (chartModel.timeType == TimeType_Year){
//            [self getYearOrMonth:NO model:chartModel];
            [self reloadTableCell:indexpath];
        }
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 前一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.row];
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }else if (chartModel.timeType == TimeType_Month){
//        [self getYearOrMonth:YES model:chartModel];
        [self reloadTableCell:indexpath];
    }else if (chartModel.timeType == TimeType_Year){
//        [self getYearOrMonth:NO model:chartModel];
        [self reloadTableCell:indexpath];
    }
}

#pragma mark ------ 后一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.row];
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }else if (chartModel.timeType == TimeType_Month){
//        [self getYearOrMonth:YES model:chartModel];
        [self reloadTableCell:indexpath];
    }else if (chartModel.timeType == TimeType_Year){
//        [self getYearOrMonth:NO model:chartModel];
        [self reloadTableCell:indexpath];
    }
}

- (void)reloadTableCell:(NSIndexPath*)indexPath{
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


@end
